import * as fs from 'fs';
import * as path from 'path';

import dotenv from 'dotenv';

const root = path.resolve(__dirname, '../');

export const resolve = (url) => path.resolve(root, url);
export const isProduction = process.env.NODE_ENV === 'production';
export const getEnvVaribles = () => {
  const envFilePath = resolve('./.env');
  const envDevFilePath = resolve('./.env.dev');
  const envObject = isProduction
    ? fs.existsSync(envFilePath)
      ? dotenv.config().parsed
      : {}
    : fs.existsSync(envDevFilePath)
    ? dotenv.config({ path: envDevFilePath }).parsed
    : {};

  const globalVariables = Object.keys(envObject).reduce((acc, key) => {
    acc[`process.env.${key}`] = JSON.stringify(envObject[key]);
    return acc;
  }, {});
  return globalVariables;
};
